package com.test.demo.test;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 消费者
 * @author Gao
 * @date 2020/8/27
 */
public class RocketConsumer {

    public static void main(String[] args) {
        // public DefaultMQPushConsumer(String consumerGroup)
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumerGroupTest");
        consumer.setNamesrvAddr("81.70.58.152:9876");
        // 接收消息后从第1条开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //消费模式:一个新的订阅组第一次启动从队列的最后位置开始消费 后续再启动接着上次消费的进度开始消费
        //consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        try {
            // 第二个参数表示消费匹配的tag * 表示topic所有的tag，一类消息，也可以是这个topic下的某些消息类型
            // public void subscribe(String topic, String subExpression) throws MQClientException
            consumer.subscribe("topic_orderCreate", "Tag-B");
            // 注册消费者监听
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext context) {
                    for (MessageExt messageExt : msgList) {
                        try {
                            System.out.println(new Date() + new String(messageExt.getBody(), "UTF-8"));
                            System.out.println("topic: " + messageExt.getTopic() + ", tags: " + messageExt.getTags());
                        } catch (Exception e) {
                            e.printStackTrace();
                            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                        }
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            // consumer 启动
            consumer.start();
            System.out.println("消费端起来了哈.........");
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
